/*
 * @Author: yijiabei
 * @Date: 2018-11-07 16:45:14
 * @Last Modified by: 李进
 * @Last Modified time: 2018-11-23 17:31:00
 */
import React, { Component } from 'react'
import { message, Button, Modal, Form, Input } from 'antd'
import Authority from './authority'
import api from '../../../api/index'
import T from '../../../lib/T'
const FormItem = Form.Item
class AddRole extends Component {
  constructor (props) {
    super(props)
    this.state = {
      resourceList: [], // 钩选的权限列表
      treeData: [], // 所有的权限列表
      parentId: [], // 默认展开的节点
      showErr: false, // 新增角色没钩选权限时 显示错误信息
      inputErr: false // 判断角色名输入框的错误信息是否在显示(输入框错误信息显示时 不再显示权限多选框的错误信息)
    }

    this.getResourceList = this.getResourceList.bind(this) // 获取选择的权限列表
    this.getAllMenus = this.getAllMenus.bind(this) // 获取全部菜单
    this.updateRole = this.updateRole.bind(this) // 根据角色ID及权限列表修改当前渠道管理员名下的角色
    this.validateRoleName = this.validateRoleName.bind(this) // 验证角色名
    this.handleOk = this.handleOk.bind(this) // 确认按钮的回调
  }

  handleOk () {
    let { resourceList } = this.state
    this.props.form.validateFields((err, values) => {
      if (!err) {
        if (this.props.action === 'add') { // 跟据父组件传过来的action类型调用不同的方法
          if (resourceList.length !== 0) {
            this.props.callBack(values.RoleName, resourceList)
          } else {
            this.setState({ showErr: true })
          }
        } else if (this.props.action === 'edit') { // 跟据父组件传过来的action类型调用不同的方法
          this.updateRole(this.props.roleId, resourceList, 'edit')
        }
      }
    })
  }
  // 修改角色权限
  updateRole (roleId, resourceList, type) {
    if (type === 'edit' && resourceList.length === 0) {
      return T.showError('Please choose at least one authorization.')
    }
    if (resourceList.length === 0) { // 用户没钩选权限或者无操作 直接点提交时取消弹框 返回页面
      // message.error('Please choose at least one authorization', 3)
      this.props.onCancel()
    } else {
      let url = api.updateRole.path
      let data = {
        roleId,
        resourceList
      }
      T.ajax({
        url,
        data,
        method: 'post',
        loading: true
      }).then((res) => {
        console.log(res)
        if (res.code === 0) {
          message.success('Authorization edited successfully', 3)
          this.props.onCancel()
        }
      })
    }
  }
  // 获取选择的权限列表
  getResourceList (resourceList, parentList) {
    let dataList = []
    let dataList2 = []
    let list = []
    resourceList.forEach(item => {
      dataList.push(item - 0) // 将ID的数据类型转成数字
    })
    parentList.forEach(item => {
      dataList2.push(item - 0) // 将ID的数据类型转成数字
    })
    // console.log('dataList', dataList)
    list = [...dataList, ...dataList2]
    if (list.length > 0) {
      this.setState({
        resourceList: list,
        showErr: false
      })
    } else {
      this.setState({
        resourceList: list
      })
      if (!this.state.inputErr) { // 判断input的错误信息是否显示
        this.setState({
          showErr: true
        })
      }
    }
  }
  componentDidMount () {
    this.getAllMenus()
  }
  // 获取全部菜单权限  需要优化 使用递归
  getAllMenus () {
    let url = api.getAllMenus.path + '/platform'
    let arr = [] // 临时存储
    let child = []
    let child2 = []
    let parentId = [] // 需要默认展开的节点ID
    T.ajax({
      url,
      method: 'get',
      data: {}, // 不需要参数
      loading: true
    }).then((res) => {
      console.log('MenusRes', res)
      if (res.code === 0) {
        res.data.forEach(item => {
          item.children.forEach(p => {
            if (p.children && p.children.length > 0) {
              p.children.forEach(s => {
                child2.push({
                  title: s.name,
                  key: s.id
                })
              })
              child.push({
                title: p.name,
                key: p.id,
                children: child2
              })
            } else {
              child.push({
                title: p.name,
                key: p.id
              })
            }
            // if (p.type !== 1) {

            // }
            // console.log(child)
          })
          parentId.push(item.id)
          arr.push({
            title: item.name,
            key: item.id,
            children: child
          })
          child = [] // 每次将子数组添加到列表里之后 清空子数组
          child2 = []
        })
        console.log('arr', arr)
        this.setState({
          treeData: arr,
          parentId
        })
      }
    })
  }
  // 删除角色名左右空格
  trim (s) {
    return s.replace(/(^\s*)|(\s*$)/g, '')
  }
  // 验证角色名是否合法
  validateRoleName (rule, value, callbackFun) {
    let val
    if (value && value.length > 0) {
      val = this.trim(value) // 有输入角色名时先去删除左右空格
    }
    if (!val || val.length === 0) { // 非空验证
      callbackFun('Please input the role name.')
      this.setState({
        inputErr: true,
        showErr: false
      })
    } else {
      this.setState({
        inputErr: false
      })
      callbackFun()
    }
    let flag = false
    for (let item of this.props.dataSource) {
      if (item.roleName === value) { // 判断角色名是否已存在
        flag = true
        break
      }
    }
    if (flag) { // 重复角色名验证
      callbackFun('Role already exists, please input another one')
    } else {
      callbackFun()
    }
  }
  render () {
    const formItemLayout = {
      labelCol: {
        sm: { span: 6 }
      },
      wrapperCol: {
        sm: { span: 18 }
      }
    }
    let title = ''
    const { getFieldDecorator } = this.props.form
    // console.log('getFieldDecorator', getFieldDecorator)
    let { action, roleId, roleName, dataSource } = this.props
    // 判断父组件传过来的action类型 add 时标题为'New Role',查看和修改时标题为角色名
    if (action === 'add') {
      title = 'New Role'
    } else {
      title = roleName
    }
    return (
      <Modal
        title={title}
        visible={this.props.visible}
        onOk={() => this.handleOk()}
        onCancel={this.props.onCancel}
        footer={[
          action === 'view'
            ? <Button key='back' type='primary' onClick={this.props.onCancel}>Back</Button>
            : <Button key='back' onClick={this.props.onCancel}>Cancel</Button>,
          action !== 'view'
            ? <Button key='submit' type='primary' onClick={() => this.handleOk()}>
            Confirm
            </Button> : null
        ]}
      >
        {
          action === 'add'
            ? <Form>
              <FormItem
                {...formItemLayout}
                label='Role Name:'
              >
                {getFieldDecorator('RoleName', {
                  rules: [{
                    validator: this.validateRoleName
                  }]
                })(
                  <Input
                    maxLength='50'
                    placeholder='Please input role name'

                  />
                )}
                {this.state.showErr ? <span className='errMsg'>Please choose at least one authorization.</span> : null}
              </FormItem>
            </Form> : null
        }
        <Authority
          roleId={roleId}
          roleName={roleName}
          treeData={this.state.treeData}
          parentId={this.state.parentId}
          getResourceList={this.getResourceList}
          action={action}
        />
      </Modal>
    )
  }
}
const AddRoleForm = Form.create()(AddRole)
export default AddRoleForm
